package cn.myeasyai.service;

import cn.myeasyai.config.FileConfig;
import cn.myeasyai.config.condition.LocalFileCondition;
import cn.myeasyai.config.condition.ObsFileCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;

/**
 * 本地文件写入
 * @author fushoujiang
 */
@Service
@ConditionalOnProperty(name = "file.model", havingValue = "local")
public class LocalFileServiceImpl implements UploadFileService {


    @Resource
    private FileConfig fileConfig;
    @Override
    public String uploadFile(InputStream inputStream, String fileName) {

        String url = fileConfig.getLocal().getPath() + fileName + ".png";
        writeToLocal(inputStream, url);
        return fileConfig.getLocal().getUrl() + fileName + ".png";
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param input 写入本地目录
     * @param input 输入流
     * @throws IOException
     */
    private void writeToLocal(InputStream input, String url) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(url);
            input.transferTo(fileOutputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
